package de.teamgamma.cansat.groundstation.database;

import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.json.JSONObject;

import de.teamgamma.cansat.groundstation.control.Controller;
import de.teamgamma.cansat.groundstation.options.OptionKeys;

/**
 * DatabaseWriter class that send the received data to the website
 * @author Alexander Ciupka
 */

public class DatabaseWriter {
	private URL url;
	private URLConnection connection;
	private String key;
	private String currentData;
	private OutputStreamWriter writer;
	private Controller controller;

	/**
	 * Contructor
	 */
	
	public DatabaseWriter() {
		controller = Controller.getInstance();
	}
	
	
	/**
	 * Gets the API Key from the Options
	 * @return API Key
	 */
	
	public String getAPIKey() {
		//refreshing the APIKey
		try {
			return URLEncoder.encode(controller.getOptions().getOptionValue(OptionKeys.APIKEY), "UTF-8") + "=";
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
	
	/**
	 * Sending the received data to website
	 */
	
	public void sendingData(JSONObject data) {
		//If not connected, it try to start the connection
		if (!isConnected()) {
			startConnection();
		}
		key = getAPIKey();
		//Gets the actual JSON-String
		if(key != null) {
			currentData = data.toString();
			try {
				//send the APIKey + the Data to the website
				writer.write(key + URLEncoder.encode(currentData, "UTF-8"));
				writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Trying to start the connection to the website
	 */
	
	public void startConnection() {
		try {
			url = new URL("http://teamgamma.noodle-net.de/add.php");
			//open the connection to the url
			connection = url.openConnection();
			connection.setDoOutput(true);
			//creates a new OutputStreamWriter
			writer = new OutputStreamWriter(connection.getOutputStream());
			System.out.println("Connection to website was successful");
		} catch (Exception e) {
			System.err.println("Connection to website was not successful");
		}
	}
	
	/**
	 * Check if there is a connection to the website
	 * @return boolean that shows if it is connected or not
	 */
	
	public boolean isConnected() {
		if (connection == null) 
			return false;
		return true;
	}
 
}
